package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login(String username, String password, HttpServletRequest request) throws IOException {
        User user = userService.login(username, password);
        if (user == null) {
            return "no";
        } else {
            request.getSession().setAttribute("user", user);

                   Object o=request.getSession().getAttribute("user");

                    System.out.println(request.getSession().getId());
            return "ok";
        }
    }

    @GetMapping("/add")
    public String add(User user,HttpServletRequest request){
        User exsitUser = userService.findByUserName(user.getUsername());
        if (exsitUser != null) {
            return "该用户名已经存在";
        } else{
           int r= userService.add(user);
            if(r>0) {
                request.getSession().setAttribute("user", user);
                return "ok";
            }else{
            return "注册失败";
            }
        }

    }


    @GetMapping("/update")
    public void updateUser(User user) {
        userService.update(user);
    }
}
